<?php

namespace app\admin\controller\outhouse;

use app\admin\model\information\Warehouse;
use app\admin\model\inventory\Kc;
use app\admin\model\outhouse\TpdjList;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use app\admin\model\outhouse\TpdjListView;
/**
 * 调拨单据管理
 *
 * @icon fa fa-circle-o
 */
class Tpdj extends Backend
{

    /**
     * Tpdj模型对象
     * @var \app\admin\model\outhouse\Tpdj
     */
    protected $model = null;
    protected $modelView = null;
    
    public function _initialize()
    {
        $this->modelView = new TpdjListView();
        parent::_initialize();
    }
    public function index(){

        $this->model =  new TpdjList();

        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        $this->searchFields = 'inv_name,inv_number,inv_specification,code,cBatch';

        //setParam(['Tpdj.createtime'=>'createtime','Tpdj.code'=>'code']);
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->modelView //$this->model
            // ->hasWhere('tpdj',$where)
            // ->with([
            //     'tpdj'=>['wareHouse','changeWareHouse'],
            //     'shelves',
            //     'changeShelves',
            // ])
            ->where($where)
            ->order('code_date desc')
            ->paginate($limit);
            
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    public function add(){
        return $this->same(2,'add');
    }

    public function commonCheckParams($params,$basic_arr,$type =1){
        if (empty($params['warehouse_id'])) {
            $this->error('没有选择仓库');
        }
        if ($type == 2 && ($params['warehouse_id'] == $params['warehouse_change_id'])) {
            $this->error('请选择不一样的仓库');
        }
        if (!array_filter(array_map('array_filter', $basic_arr))) {
            $this->error('请填写要调拨的库存');
        }

    }

    public function same($type = 1,$template = 'same'){

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $basic_json    = $params['basic'];
            $basic_arr     = json_decode($basic_json, true);

            $this->commonCheckParams($params,$basic_arr,$type);

            try {
                Db::startTrans();
                $params['code'] = $code  = 'DB'.uniqid_date_code();
                $params['type'] = $type;//同仓库调拨
                 \app\admin\model\outhouse\Tpdj::addData($params); //添加表头
                $tpdjList = [];
                foreach ($basic_arr as $k => $v) {
                    if(empty($v['shelves_change_id'])){
                        Db::rollback();
                        throw  new Exception('请选择货架');
                    }
                    if(empty($v['tp_iQuantity'])){
                        Db::rollback();
                        throw  new Exception('请选择填写数量');
                    }

                    $tpdjList[] = [
                        'code'=>$code,
                        'kc_id'=>$v['id'],
                        'shelves_id'=>$v['shelves_id'],
                        'shelves_change_id'=>$v['shelves_change_id'],
                        'cInvCode'=>$v['cInvCode'],
                        'tp_iQuantity'=>$v['tp_iQuantity'],
                        'createtime'=>date('Y-m-d H:i:s'),
                    ];
                }
                //添加调拨单货物列表
                Db::name('tpdj_list')->insertAll($tpdjList);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
         $this->success($template);
        }

        return $this->fetch();
    }

    /**
     * 通用参数
     * @param $id
     * @param $warehouseCode
     * @param $cInvCode
     * @param $iQuantity
     * @param $cFree1
     * @return array
     */
    public function commonKcParams($id,$warehouseCode,$cInvCode,$iQuantity,$cFree1){
        $updateData = [
            'id'=>$id,
            'AutoID' => '',
            'cWhCode' => $warehouseCode,
            'cInvCode' => $cInvCode,
            'cBatch' => '',
            'iQuantity' => $iQuantity,
            'cFree1' => $cFree1,
            'dMdate' => '',
            'dVDate' => '',
            'iMassDate' => '',
            'dLastCheckDate' => '',
        ];
        return $updateData;
    }
    public function edit($ids = null)
    {
        if($this->request->isPost()){

            $params = $this->request->post("row/a");
            $basic_json    = $params['basic'];
            $basic_arr     = json_decode($basic_json, true);
            $this->commonCheckParams($params,$basic_arr);

            $tpdjList = [];
            foreach ($basic_arr as $k => $v) {

                if(empty($v['shelves_change_id'])){
                    Db::rollback();
                    throw new Exception('请选择货架');
                }
                if(empty($v['tp_iQuantity'])){
                    Db::rollback();
                    throw new Exception('请选择填写数量');
                }

                $tpdjList[] = [
                    'code'=>$params['code'],
                    'kc_id'=>$v['id'],
                    'shelves_id'=>$v['shelves_id'],
                    'shelves_change_id'=>$v['shelves_change_id'],
                    'cInvCode'=>$v['cInvCode'],
                    'tp_iQuantity'=>$v['tp_iQuantity'],
                    'createtime'=>date('Y-m-d H:i:s'),
                ];
            }
            //添加调拨单货物列表
            Db::name('tpdj_list')->where(['code'=>$params['code']])->delete();
            Db::name('tpdj_list')->insertAll($tpdjList);
            $this->success();
        }
        $code = Db::name('tpdj_list')
            ->where(['id' => $ids])
            ->value('code');
        $list =  Db::name('tpdj_list')->alias('l')
            ->join('inventory i','i.number=l.cInvCode','left')
            ->join('shelves s','s.id=l.shelves_id','left')
            ->join('shelves cs','cs.id=l.shelves_change_id','left')
            ->join('kc kc','kc.id=l.kc_id','left')
            ->field('l.shelves_change_id,l.shelves_id,l.cInvCode,l.tp_iQuantity,kc.iQuantity,l.kc_id as id,i.name,i.number,i.specification,i.unit,s.name as shname,cs.name as change_shname,l.shelves_change_id')
            ->where(['code'=>$code])->select();
        $row = Db::name('tpdj')->where(['code'=>$code])->find();
        $this->assign('list_json',json_encode($list));
        $this->assign('row',Db::name('tpdj')->where(['code'=>$code])->find());
        return $this->view->fetch($row['type']==1?'same_edit':'edit');
    }

    public function checkStatus($ids  = null){
        $rdinrecordListInfo  = Db::name('tpdj_list')->where(['id'=>$ids])->find();

        if(empty($rdinrecordListInfo)){
            $this->error('单据不存在');
        }
        $code = $rdinrecordListInfo['code'];
        $where['code'] = $code;
        $info = Db::name('tpdj')->where($where)->find();
        if($info['status']==1){
            $this->error('单据已审核');
        }
        $list = Db::name('tpdj_list')
            ->alias('l')
            ->join('tpdj t','l.code=t.code')
            ->where(['l.code'=>$code])
            ->field('l.*,t.warehouse_id,t.warehouse_change_id,t.type,t.code,t.code_date')
            ->where('l.id','in',$ids)
            ->select();
        try {
            Db::startTrans();
            foreach ($list as $k=>$v){
                $warehouseCode = Db::name('warehouse')->where(['id'=>$v['warehouse_id']])->value('number');
                Kc::tbdjUpdataKc($v,$warehouseCode);
                Db::name('tpdj')->where(['code'=>$v['code']])->update(['status'=>1]);
            }
            Db::commit();
        }catch (ValidateException|PDOException|Exception $e){
            Db::rollback();
            throw new Exception($e->getMessage());
        }

        $this->success();
    }

    /**
     * 通用参数
     * @param $code
     * @param $code_date
     * @param $quantity
     * @param $cInvCode
     * @param $cFree1
     * @param $shelves_change_id
     * @return array
     */
    public function commonKcmxParams($code,$code_date,$quantity,$cInvCode,$cFree1,$shelves_change_id){
        $kcmxData = [
            'order_code' => $code,
            'order_date' => $code_date,
            'order_list' => 4,
            'quantity' => $quantity,
            'cInvCode' => $cInvCode,
            'cFree1' => $cFree1,
            'shelves_id' =>$shelves_change_id,
        ];
        return $kcmxData;
    }

    /**
     * 插入中间库
     * @param $data
     * @param $list
     * @return void
     * @throws \think\Exception
     */
    public function insertMiddlData($data,$list)
    {
        //插入中间库
        $insert_id = Db::connect('database.inc')->table('TransVouch')->insertGetId([
            'cTVCode' => $data['code'],
            'dTVDate' =>$data['code_date'] ,
            'cOWhCode' => $data['warehouse_code'],
            'cIWhCode' => $data['change_warehouse_code'],
            'dnmodifytime'=>date('Y-m-d H:i:s'),
            'ID'=>time(),
        ]);
        foreach ($list as $k=>$v){
            Db::connect('database.inc')->table('TransVouchs')->insert([
                'cTVCode'=>$data['code'],
                'cInvCode'=>$v['cInvCode'],
                'ID' => $insert_id,
                'autoID'=>time(),
                'iTVQuantity' => $v['iQuantity'],
            ]);
        }
    }

}